<template>
  <div>
    <selected @getreqList="getreqList" />
    <el-card v-show="scene==0">
      <el-button type="primary" icon="el-icon-plus" @click="addSpu">添加spu</el-button>
      <el-table
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="序号"
          width="160"
        />
        <el-table-column
          prop="spuName"
          label="spu名称"
          width="300"
        />
        <el-table-column
          prop="description"
          label="spu描述"
          width="400"
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="success"
              icon="el-icon-plus"
              @click="handleAdd(scope.$index, scope.row)"
            />
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleSpuEdit(scope.$index, scope.row)"
            />
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDeleteSpu(scope.$index, scope.row)"
            />

            <el-button
              size="mini"
              type="info"
              icon="el-icon-message"
              @click="handleInfo(scope.$index, scope.row)"
            />

          </template>
        </el-table-column>
      </el-table>
      <!--            current-page当前页数  page-size每页条数 page-sizes每页显示个数选择器的选项设置  layout布局-->
      <el-pagination
        :current-page="page"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!--    添加spu 的模板-->
    <el-card v-show="scene==1">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="spu名称">
          <el-input v-model="spuData.spuName" />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in taramarkList"
              :key="item.id"
              :label="item.tmName"
              :value="item.tmName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="spu描述">
          <el-input
            v-model="spuData.description"
            type="textarea"
            placeholder="请输入内容"
            maxlength="30"
            show-word-limit
          /></el-form-item>
        <el-form-item label="spu图片">
          <el-upload
            action="/dev-api/admin/product/fileUpload"
            list-type="picture-card"
            :on-success="handleAvatarSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :file-list="imagesList"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl">
          </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
          <el-select v-model="salevalue" placeholder="请选择">
            <el-option v-for="item1 in unShowsale" :key="item1.id" :value="`${item1.id}:${item1.name}`" :label="item1.name" />
          </el-select>
          <el-button type="primary" icon="el-icon-plus" style="margin-left: 20px" :disabled="salevalue?false:true" @click="addSaleValue">添加销售属性</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="spuData.spuSaleAttrList"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="序号"
          width="100"
        />
        <el-table-column
          prop="saleAttrName"
          label="属性名"
          width="180"
        />
        <el-table-column
          prop="spuSaleAttrValueList"
          label="属性名称列表"
        >
          <template slot-scope="scope">

            <el-tag v-for="(tag,index) in scope.row.spuSaleAttrValueList" :key="tag.name" type="success" closable style="margin-right: 20px" @close="scope.row.spuSaleAttrValueList.splice(index,1)"> {{ tag.saleAttrValueName }}</el-tag>
            <el-button v-if="!scope.row.isisAdd" @click="addattrValue(scope)">添加</el-button>
            <el-input v-if="scope.row.isisAdd" v-model="scope.row.attrvalue" size="mini" style="width: 80px" @blur="addsaleAttrValueName(scope)" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!--            <el-button-->
            <!--              size="mini"-->
            <!--              @click="handleEdit(scope.$index, scope.row)"-->
            <!--            >编辑</el-button>-->
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteAttrValue(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 40px">
        <el-button type="primary" @click="saveSpu"> 保存</el-button>
        <el-button @click="cacleSpu"> 取消</el-button>
      </div>
    </el-card>
    <skuFrom ref="skufrom" :spu-list="spuList" @changescene="changescene" />
    <!--    sku 实例的对话框-->
    <el-dialog :title="`${title}的sku列表`" :visible.sync="dialogTableVisible" @close="closeLoding">
      <el-table v-loading="loading" :data="gridData">
        <el-table-column property="skuName" label="名称" width="150" />
        <el-table-column property="price" label="价格" width="200" />
        <el-table-column property="weight" label="重量" />
        <el-table-column label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.skuDefaultImg" style="width: 100px;height: 100px">
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import selected from '@/views/shop/select'
import skuFrom from '@/views/shop/skuFrom/skuFrom'
import {
  reqApu,
  reqBaseSaleAttrList, reqDeleteSpu,
  reqEditAttr,
  reqImageList,
  reqsaveAttr,
  reqSpuList,
  reqTardMarkList,
  reqSpuById
} from '@/api/spu'
export default {
  name: 'Spu',
  components: {
    selected,
    skuFrom
  },
  data() {
    return {
      page: 1,
      limit: 3,
      total: 0,
      spuList: {},

      tableData: [],

      form: {},
      // 对话框相关的3个数据
      dialogTableVisible: false,
      gridData: [],
      title: '',
      loading: true,
      // 定义一个场景  切换table和添加或者编辑
      scene: 0,
      value: '',
      // 销售属性的
      salevalue: '',
      // 编辑时当前数据的信息
      spuData: {
        spuSaleAttrList: []
      },
      // 品牌的数组
      taramarkList: [],
      // 图片的数组
      imagesList: [],
      // 平台销售属性
      saleList: [],
      // 请求参数
      reqsave: {},
      // 照片墙的数据
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    // saleList销售的属性列表  过滤出已经已有的销售属性 显示未选中的销售属性
    unShowsale() {
      if (!this.spuData.spuSaleAttrList || this.spuData.spuSaleAttrList.length === 0) {
        return this.saleList
      } else {
        return this.saleList.filter((item) => {
          return this.spuData.spuSaleAttrList
        }).filter((item) => {
          return this.spuData.spuSaleAttrList.every((i) => item.name !== i.saleAttrName)
        })
      }
    }
  },
  methods: {
    getreqList(list) {
      this.spuList = list
      this.getSpuData()
    },
    // 发请求
    async getSpuData() {
      const { page, limit } = this
      const res = await reqSpuList(page, limit, this.spuList.category3Id)
      if (res.code === 200) {
        this.total = res.data.total
        this.tableData = res.data.records
      }
    },
    handleSizeChange(pageSize) {
      this.limit = pageSize
      this.getSpuData()
    },
    handleCurrentChange(pageNo) {
      this.page = pageNo
      this.getSpuData()
    },
    // on-remove	文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      // file就是被移除的
      console.log(file, fileList)
    },
    // on-preview	点击文件列表中已上传的文件时的钩子  图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 文件上传成功的钩子
    handleAvatarSuccess(response, file, fileList) {
      console.log('fileList', fileList)
      fileList.forEach((item) => {
        item.imgName = item.name
        item.imgUrl = item.url
      })
      this.spuData.spuImageList = fileList
    },
    // 这块时编辑
    async handleSpuEdit(index, row) {
      this.scene = 1
      // 点击编辑发送请求
      const res = await reqApu(row.id)
      if (res.code == 200) {
        this.spuData = res.data
      }
      // 获取品牌
      const tradmarkres = await reqTardMarkList()
      if (tradmarkres.code === 200) {
        this.taramarkList = tradmarkres.data
      }
      // 获取图标
      const resImage = await reqImageList(row.id)
      if (resImage.code === 200) {
        // console.log('img请求', resImage.data)
        // 因为照片墙需要name 和url字段  所以需要修改服务器数据，以下代码相当于给item新增了一个name和url 数据
        const list = resImage.data
        list.forEach((item) => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.imagesList = list
        // console.log('sss', this.imagesList)
      }
      const resSaleAttrlist = await reqBaseSaleAttrList()
      if (resSaleAttrlist.code === 200) {
        this.saleList = resSaleAttrlist.data
      }
    },
    // 添加属性值
    addattrValue({ row }) {
      // 添加一个响应式数据
      this.$set(row, 'isisAdd', true)
      this.$set(row, 'attrvalue', '')
    },
    //  input 属性值Input失去焦点的回调
    addsaleAttrValueName({ row }) {
      // console.log('row', row)
      row.isisAdd = false
      const { attrvalue, baseSaleAttrId } = row
      const obj = {
        baseSaleAttrId: baseSaleAttrId,
        saleAttrValueName: attrvalue
      }
      console.log('xxx', row.spuSaleAttrValueList)
      row.spuSaleAttrValueList.push(obj)
    },
    // 添加属性
    addSaleValue() {
      const res = this.salevalue.split(':')
      const obj = {
        baseSaleAttrId: res[0],
        saleAttrName: res[1],
        spuSaleAttrValueList: []
      }
      console.log('this.spuData.spuSaleAttrList', this.spuData.spuSaleAttrList)
      this.spuData.spuSaleAttrList.push(obj)
    },
    // 删除属性
    handleDeleteAttrValue(index, row) {
      console.log(index)
      this.spuData.spuSaleAttrList.splice('index', 1)
    },
    // 点击保存
    async saveSpu() {
      if (this.spuData.id) {
        console.log('我是编辑')
        const res = await reqEditAttr(this.spuData)
        if (res.code === 200) {
          this.scene = 0
          this.getSpuData()
          this.$message.success('修改成功')
          this.spuData = {}
        }
      } else {
        this.spuData.category3Id = this.spuList.category3Id
        const res = await reqsaveAttr(this.spuData)
        console.log(res)
        if (res.code == 200) {
          this.scene = 0
          this.$message.success('新增成功')
          this.getSpuData()
        }
        this.spuData = {
          spuSaleAttrList: []
        }
      }
    },
    // 这块是添加
    async addSpu() {
      this.scene = 1
      // 发送两个请求
      // 获取品牌
      const tradmarkres = await reqTardMarkList()
      if (tradmarkres.code === 200) {
        this.taramarkList = tradmarkres.data
      }
      const resSaleAttrlist = await reqBaseSaleAttrList()
      if (resSaleAttrlist.code === 200) {
        this.saleList = resSaleAttrlist.data
      }
    },
    // 点击取消
    cacleSpu() {
      this.scene = 0
      this.spuData = {}
    },
    // 删除spu
    async handleDeleteSpu(index, row) {
      const res = await reqDeleteSpu(row.id)
      console.log(res)
      if (res.code === 200) {
        this.$message.success('删除成功')
        this.getSpuData()
      }
    },
    handleAdd(index, row) {
      this.scene = 2
      this.$refs.skufrom.scene = 2
      this.$refs.skufrom.spuName = row.spuName
      this.$refs.skufrom.id = row.id
      this.$refs.skufrom.getdata()
    },
    changescene() {
      console.log('一切换')
      this.scene = 0
      this.getSpuData()
    },
    //  查看当前spu 下面所有的sku实例
    async handleInfo(index, row) {
      console.log(row)
      const res = await reqSpuById(row.id)
      if (res.code === 200) {
        this.loading = false
        this.title = row.spuName
        this.gridData = res.data
        this.dialogTableVisible = true
      }
    },
    // 解决Loading只执行一次
    closeLoding() {
      console.log('重新加载')
      this.loading = true
      this.gridData = []
    }
  }
}
</script>

<style scoped>

</style>
